using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;


/*
* Introduction：
* Creator：
*/
namespace HyxFrame.Core
{



    /// <summary>
    /// 
    /// </summary>
    public class DownloadManager : MonoSingleton<DownloadManager>
    {

        private Queue<DownloadTask> downloadQueue = new Queue<DownloadTask>();
        private DownloadTask currentDownloadTask;

        // 新增：用于更新进度条的回调
        private Action<float> onProgressUpdated;

        public void AddDownloadTask(string url, string savePath, Action onComplete, Action<float> onProgressUpdated = null)
        {
            DownloadTask task = new DownloadTask(url, savePath, onComplete);
            downloadQueue.Enqueue(task);

            // 新增：设置进度更新回调
            this.onProgressUpdated = onProgressUpdated;

            if (currentDownloadTask == null)
            {
                StartNextDownload();
            }
        }

        private void StartNextDownload()
        {
            if (downloadQueue.Count > 0)
            {
                currentDownloadTask = downloadQueue.Dequeue();
                StartCoroutine(DownloadCoroutine(currentDownloadTask));
            }
        }

        private IEnumerator DownloadCoroutine(DownloadTask task)
        {
            using (UnityWebRequest www = UnityWebRequest.Get(task.Url))
            {
                //// 新增：设置下载进度回调
                //www.downloadProgressChanged += (progress) =>
                //{
                //    onProgressUpdated?.Invoke(progress);
                //};

                yield return www.SendWebRequest();

                if (www.result == UnityWebRequest.Result.Success)
                {
                    System.IO.File.WriteAllBytes(task.SavePath, www.downloadHandler.data);
                    task.OnComplete?.Invoke();
                }
                else
                {
                    Debug.LogError("Download error: " + www.error);
                }

                currentDownloadTask = null;
                // 新增：重置进度回调为null
                onProgressUpdated = null;

                StartNextDownload();
            }
        }

        protected override void InitManager()
        {

        }

        private class DownloadTask
        {
            public string Url { get; }
            public string SavePath { get; }
            public Action OnComplete { get; }

            public DownloadTask(string url, string savePath, Action onComplete)
            {
                Url = url;
                SavePath = savePath;
                OnComplete = onComplete;
            }
        }

    }
}